package com.ycxy.sh.transaction.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ycxy.sh.transaction.dao.entity.*;
import com.ycxy.sh.transaction.dao.vo.LayuiPageVo;
import com.ycxy.sh.transaction.dao.vo.PageVo;
import com.ycxy.sh.transaction.dao.vo.UserInfoStandardVo;
import com.ycxy.sh.transaction.ex.ServiceException;
import com.ycxy.sh.transaction.mapper.*;
import com.ycxy.sh.transaction.service.CollectService;
import com.ycxy.sh.transaction.service.CommodityService;
import com.ycxy.sh.transaction.util.KeyUtil;
import com.ycxy.sh.transaction.web.JsonResult;
import com.ycxy.sh.transaction.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商品信息实现类
 * @author hlt
 * @since 2019-12-21
 */
@Slf4j
@Service
@Transactional
public class CommodityServiceImpl implements CommodityService {
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private CommodityimagesMapper commodityimagesMapper;

    @Autowired
    private NoticesMapper noticesMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private CommoditySoldrecordMapper soldrecordMapper;


    /**插入商品*/
    @Async
    public Integer InsertCommodity(Commodity commodity){
        return commodityMapper.InsertCommodity(commodity);
    }
    /**查询商品详情*/
    public String LookCommodity(Long commid, ModelMap modelMap, HttpSession session){

        Long couserid = (Long) session.getAttribute("userid");

        //根据商品id和商品状态（Commstatus）查询商品
        Commodity commodity = commodityMapper.selectById(new Commodity().setCommodityId(commid).setCommodityStatus(1));
        int i = 0;
        if (commodity.getCommodityStatus().equals(1)){//如果商品正常
            i=1;
        }else if (!StringUtils.isEmpty(couserid)){//如果用户已登录
            Login login = loginMapper.userLogin(new Login().setUserId(couserid));
            /**商品为违规状态时：本人和管理员可查看*/
            if (commodity.getCommodityStatus().equals(0) && (commodity.getUserId().equals(couserid) || (login.getRoleId().equals(2) || login.getRoleId().equals(3)))){
                i=1;
                /**商品为待审核状态时：本人和管理员可查看*/
            }else if (commodity.getCommodityStatus().equals(3) && (commodity.getUserId().equals(couserid) || (login.getRoleId().equals(2) || login.getRoleId().equals(3)))){
                i=1;
                /**商品为已售出状态时：本人和管理员可查看*/
            }else if (commodity.getCommodityStatus().equals(4) && (commodity.getUserId().equals(couserid) || (login.getRoleId().equals(2) || login.getRoleId().equals(3)))){
                i=1;
            }
        }
        if(i==1){
            commodity.setOtherimg(commodityimagesMapper.selectGoodImages(commid));
            /**商品浏览量+1*/
            commodityMapper.updateCommodity(new Commodity().setCommodityId(commid).setPageView(1));
            modelMap.put("userinfo", userInfoMapper.selectPartInfo(commodity.getUserId()));
            modelMap.put("gddetail",commodity);
            //如果没有用户登录
            if (StringUtils.isEmpty(couserid)){
                modelMap.put("collectstatus",2);
            }else {
                Collect collect = collectMapper.selectStatus(new Collect().setCommodityId(commid).setCollectUserId(couserid));
                if(collect!=null){
                    if (collect.getCollectStatus() == 2){
                        modelMap.put("collectstatus",2);
                    }else {
                        modelMap.put("collectstatus",1);
                    }
                }else {
                    modelMap.put("collectstatus",2);
                }
            }
            return "/common/product-detail";
        }else{
            return "/error/404";
        }
    }

    /**
     * 修改商品
     * @param commodity
     * @return
     */
    @Override
    public void updateCommodity(Commodity commodity, HttpSession session) {
        Long userid = (Long) session.getAttribute("userid");
        commodity.setUpdateTime(new Date()).setCommodityStatus(3);
        commodity.setCommon(commodity.getCommon()+"、"+commodity.getCommon2());//常用选项拼接
        //修改商品
        commodityMapper.updateCommodity(commodity);
        commodityimagesMapper.DelGoodImages(commodity.getCommodityId());
        List<CommodityImages> commodityImagesList =new ArrayList<>();
        for (String list:commodity.getOtherimg()) {
            commodityImagesList.add(new CommodityImages().setId(Long.valueOf(KeyUtil.genUniqueKey())).setCommodityId(commodity.getCommodityId()).setImage(list));
        }
        int rowList = commodityimagesMapper.InsertGoodImages(commodityImagesList);
        if(rowList<1){
            String message="插入商品其他图失败";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        /**发出待审核系统通知*/
        Notices notices = new Notices().setId(Long.valueOf(KeyUtil.genUniqueKey())).setUserId(userid).setNoticeType("商品审核")
                .setNoticeContent("您的商品 <a href=/product-detail/"+commodity.getCommodityId()+" style=\"color:#08bf91\" target=\"_blank\" >"+commodity.getCommodityName()+"</a> 进入待审核队列，请您耐心等待。");
        int row = noticesMapper.insert(notices);
        if(row!=1){
            String message="查询失败,请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_SELECT,message);
        }
    }

    /**
     * 发布商品
     * @param commodity
     * @param session
     */
    public void publishCommodity(Commodity commodity, HttpSession session){
        Long userid = (Long) session.getAttribute("userid");
        UserInfoStandardVo userInfo = userInfoMapper.selectUserinfo(userid);
        //使用工具类生成唯一id
        Long commid = Long.valueOf(KeyUtil.genUniqueKey());
        commodity.setCommodityId(commid).setUserId(userid).setProductLocation(userInfo.getCity());//商品id
        commodity.setCommon(commodity.getCommon()+"、"+commodity.getCommon2());//常用选项拼接
        //新增商品
        int i = commodityMapper.InsertCommodity(commodity);
        if(i!=1){
            String message="插入商品失败";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        List<CommodityImages> commodityImagesList =new ArrayList<>();
        for (String list:commodity.getOtherimg()) {
            commodityImagesList.add(new CommodityImages().setId(Long.valueOf(KeyUtil.genUniqueKey())).setCommodityId(commid).setImage(list));
        }
        commodityimagesMapper.InsertGoodImages(commodityImagesList);
        /**发出待审核系统通知*/
        Notices notices = new Notices().setId(Long.valueOf(KeyUtil.genUniqueKey())).setUserId(userid).setNoticeType("商品审核")
                .setNoticeContent("您的商品 <a href=/product-detail/"+commid+" style=\"color:#08bf91\" target=\"_blank\" >"+commodity.getCommodityName()+"</a> 进入待审核队列，请您耐心等待。");
        //插入一条公告
        int row = noticesMapper.insert(notices);{
            String message="插入公告失败";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    /**
     * 上传视频和主图
     * @param file
     * @return
     */
    @Override
    public JSONObject uploadVideo(MultipartFile file) throws IOException {
        JSONObject res = new JSONObject();
        JSONObject resUrl = new JSONObject();
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String filenames = filename + "." + ext;
        String pathname = "D:/dn-img" + filenames;
        file.transferTo(new File(pathname));
        resUrl.put("src", "/pic/"+filenames);
        res.put("msg", "");
        res.put("code", 0);
        res.put("data", resUrl);
        return res;
    }

    /**
     * 上传其他图片
     * @param file
     * @return
     */
    @Override
    public JSONObject uploadImages(MultipartFile[] file) {
        JSONObject res = new JSONObject();
        JSONObject resUrl = new JSONObject();
        List<String> imageurls=new ArrayList<>();
        for (MultipartFile files:file){
            String filename = UUID.randomUUID().toString().replaceAll("-", "");
            String ext = FilenameUtils.getExtension(files.getOriginalFilename());
            String filenames = filename + "." + ext;
            String pathname ="D:/dn-img"  + filenames;
            try {
                files.transferTo(new File(pathname));
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageurls.add("/pic/"+filenames);
            res.put("msg", "");
            res.put("code", 0);
        }
        resUrl.put("src", imageurls);
        res.put("data", resUrl);
        return res;
    }

    /**分页查询商品总数*/
    public int queryCommodityByNameCount(String commname){
        int dataNumber = commodityMapper.queryCommodityByNameCount("%"+commname+"%");
        if(dataNumber<1){
            String message="分页商品失败,数据不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return dataNumber;
    }

    /**
     * 搜索商品
     * @param page
     * @param commname
     */
    @Override
    public List<Commodity> searchCommodity(Integer page, String commname) {
        List<Commodity> commodityList = commodityMapper.queryCommodityByName((page - 1) * 20, 20, commname);

        if(!StringUtils.isEmpty(commodityList)){//如果有对应商品
            String message="相关商品不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }else{
            for (Commodity commodity : commodityList) {
                /**查询商品对应的其它图片*/
                List<String> imagesList = commodityimagesMapper.selectGoodImages(commodity.getCommodityId());
                commodity.setOtherimg(imagesList);
            }
        }
        if(commodityList==null){
            String message="相关商品不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return commodityList;
    }

    /**
     * 首页分类展示商品
     * @param category
     * @return
     */
    @Override
    public List<Commodity> indexCommodity(String category) {
        List<Commodity> commodityList = commodityMapper.queryCommodityByCategory(category);
        for (Commodity commodity : commodityList) {
            /**查询商品对应的其它图片*/
            List<String> imagesList = commodityimagesMapper.selectGoodImages(commodity.getCommodityId());
            commodity.setOtherimg(imagesList);
        }
        if(commodityList==null){
            String message="相关商品不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return commodityList;
    }

    /**
     * 查询最新发布的8条商品
     * @return
     */
    @Override
    public List<Commodity> latestCommodit() {
        String category = "全部";
        List<Commodity> commodityList = commodityMapper.queryCommodityByCategory(category);
        for (Commodity commodity : commodityList) {
            /**查询商品对应的其它图片*/
            List<String> imagesList = commodityimagesMapper.selectGoodImages(commodity.getCommodityId());
            commodity.setOtherimg(imagesList);
        }
        if(commodityList==null){
            String message="相关商品不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return commodityList;
    }

    /**
     * 产品清单分页数据
     * @param category
     * @param area
     * @param minmoney
     * @param maxmoney
     * @param session
     * @return
     */
    @Override
    public int productListNumber(String category, String area, BigDecimal minmoney, BigDecimal maxmoney, HttpSession session) {
        String productLocation=null;
        if(!area.equals("全部")){
            Long userid = (Long) session.getAttribute("userid");
            //查询用户信息
            UserInfoStandardVo userInfo = userInfoMapper.selectUserinfo(userid);
            if(StringUtils.isEmpty(userInfo)){
                String message="用户信息不存在";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
            }
            //将商品所在地设置为用户所在城市
            productLocation = userInfo.getCity();
        }
        int dataNumber = commodityMapper.queryAllCommodityByCategoryCount(area, productLocation, category, minmoney, maxmoney);
        if(dataNumber<1){
            String message="商品信息不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return dataNumber;
    }
    /**
     * 查询产品清单界面
     * @param category
     * @param page
     * @param area
     * @param minmoney
     * @param maxmoney
     * @param price
     * @param session
     * @return
     */
    @Override
    public List<Commodity> productInventory(String category, Integer page, String area, BigDecimal minmoney, BigDecimal maxmoney, Integer price, HttpSession session) {
        String productLocation=null;
        if(!area.equals("全部")) {
            Long userid = (Long) session.getAttribute("userid");
            //查询用户信息
            UserInfoStandardVo userInfoStandardVo = userInfoMapper.selectUserinfo(userid);
            if(StringUtils.isEmpty(userInfoStandardVo)){
                String message="用户信息不存在";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
            }
            //将商品所在地设置为用户所在城市
            productLocation = userInfoStandardVo.getCity();
        }
        List<Commodity> commodityList = commodityMapper.queryAllCommodityByCategory((page - 1) * 16, 16, area, productLocation, category, minmoney, maxmoney);
        for (Commodity commodity : commodityList) {
            /**查询商品对应的其它图片*/
            List<String> imagesList = commodityimagesMapper.selectGoodImages(commodity.getCommodityId());
            if(imagesList==null){
                String message="未查询到该商品存在其他的图片";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
            }
            commodity.setOtherimg(imagesList);
        }
        /**自定义排序*/
        if (price != 0){
            if (price == 1){
                /**升序*/
                Collections.sort(commodityList, new Comparator<Commodity>() {//此处创建了一个匿名内部类
                    int i;
                    @Override
                    public int compare(Commodity o1, Commodity o2) {
                        if (o1.getSellingPrice().compareTo(o2.getSellingPrice()) > -1) {
                            System.out.println("===o1大于等于o2===");
                            i = 1;
                        } else if (o1.getSellingPrice().compareTo(o2.getSellingPrice()) < 1) {
                            i = -1;
                            System.out.println("===o1小于等于o2===");
                        }
                        return i;
                    }
                });
            }else if (price == 2){
                /**降序*/
                Collections.sort(commodityList, new Comparator<Commodity>() {//此处创建了一个匿名内部类
                    int i;
                    @Override
                    public int compare(Commodity o1, Commodity o2) {
                        if (o1.getSellingPrice().compareTo(o2.getSellingPrice()) > -1) {
                            System.out.println("===o1大于等于o2===");
                            i = -1;
                        } else if (o1.getSellingPrice().compareTo(o2.getSellingPrice()) < 1) {
                            System.out.println("===o1小于等于o2===");
                            i = 1;
                        }
                        return i;
                    }
                });
            }
        }
        return commodityList;
    }

    /**
     * 分页展示个人各类商品信息
     * @param commstatus
     * @param limit
     * @param page
     * @param session
     * @return
     */
    @Override
    public LayuiPageVo pageUserCommodity(Integer commstatus, int limit, int page, HttpSession session) {
        Long userid = (Long) session.getAttribute("userid");
        //如果未登录，给一个假id
        if(StringUtils.isEmpty(userid)){
            userid = Long.valueOf("123456");
        }
        List<Commodity> commodityList=null;
        int dataNumber;
        if(commstatus==100){
            commodityList = commodityMapper.queryAllCommodity((page - 1) * limit, limit, userid,null);
            dataNumber = commodityMapper.queryCommodityCount(userid,null);
        }else{
            commodityList = commodityMapper.queryAllCommodity((page - 1) * limit, limit, userid,commstatus);
            dataNumber = commodityMapper.queryCommodityCount(userid,commstatus);
        }
        return new LayuiPageVo("",0,dataNumber,commodityList);
    }

    /**
     * 用户根据商品id修改商品信息
     * @param commid
     * @param commstatus
     * @param session
     */
    @Override
    public void ChangeCommdotityStatus(Long commid, Integer commstatus, HttpSession session) {
        int i = commodityMapper.ChangeCommstatus(commid, commstatus);
        if (i == 1){
            /**如果商品已售出*/
            if (commstatus == 4){
                Long userid = (Long) session.getAttribute("userid");
                /**根据商品id查询售出商品的信息*/
                Commodity commodity = commodityMapper.selectById(new Commodity().setCommodityId(commid));
                SoldRecord soldrecord = new SoldRecord();
                /**将商品信息添加到售出记录中*/
                soldrecord.setSoldId(Long.valueOf(KeyUtil.genUniqueKey()))
                        .setCommodityId(commid).setCommodityName(commodity.getCommodityName())
                        .setCommodityDescribe(commodity.getCommodityDescribe())
                        .setSellingPrice(commodity.getSellingPrice()).setUserId(userid);
                /**添加售出记录*/
                soldrecordMapper.insert(soldrecord);
            }
            log.debug("商品已成功修改");
        }
        String message="操作失败,请稍后重试";
        log.debug(message);
        throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
    }

    @Override
    public Commodity LookCommodity(Commodity commodity) {
        return commodityMapper.selectById(commodity);
    }


//    /**修改商品状态*/
//    public Integer ChangeCommstatus(String commid,Integer commstatus){
//        return commodityMapper.ChangeCommstatus(commid,commstatus);
//    }
//    /**通过商品名分页模糊查询*/
//    public List<Commodity> queryCommodityByName(Integer page,Integer count,String commname){
//        return commodityMapper.queryCommodityByName(page,count,"%"+commname+"%");
//    }
//    /**分页展示各类状态的商品信息*/
//    public List<Commodity> queryAllCommodity(Integer page,Integer count,String userid,Integer commstatus){
//        return commodityMapper.queryAllCommodity(page,count,userid,commstatus);
//    }
//    /**查询商品各类状态的总数*/
//    public Integer queryCommodityCount(String userid,Integer commstatus){
//        return commodityMapper.queryCommodityCount(userid,commstatus);
//    }
//    /**首页分类展示8条商品*/
//    public List<Commodity> queryCommodityByCategory(String category){
//        return commodityMapper.queryCommodityByCategory(category);
//    }
//    /**产品清单分类分页展示商品*/
//    public List<Commodity> queryAllCommodityByCategory(Integer page,Integer count,String area,String school,String category,BigDecimal minmoney,BigDecimal maxmoney){
//        return commodityMapper.queryAllCommodityByCategory(page,count,area,school,category,minmoney,maxmoney);
//    }
//    /**查询产品清单分类分页展示商品的总数*/
//    public Integer queryAllCommodityByCategoryCount(String area, String school, String category, BigDecimal minmoney, BigDecimal maxmoney){
//        return commodityMapper.queryAllCommodityByCategoryCount(area,school,category,minmoney,maxmoney);
//    }
}
